package top.lingchen.blogapi.handler;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import static top.lingchen.blogapi.vo.ErrorCode.*;

import top.lingchen.blogapi.bean.SysUser;
import top.lingchen.blogapi.service.TokenService;
import top.lingchen.blogapi.utils.UserThreadLocal;
import top.lingchen.blogapi.vo.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 凌宸
 * @create 2021-12-16 下午 8:11
 * @Description
 * @Version 1.0
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1. 需要判断请求的接口路径是否为 HandlerMethod (controller 为例)
         * 2. 判断 token 是否为空，如果为空，则未登录，需要拦截
         * 3. 如果 token 不为空，登录验证
         * 4. 如果认证成功，放行即可
         */
        if(!(handler instanceof HandlerMethod)){
            // 静态资源放行
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if(!StringUtils.hasLength(token)){
            Result result = Result.fail(NO_LOGIN.getCode(), NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        SysUser sysUser = tokenService.checkToken(token);
        if(sysUser == null){
            Result result = Result.fail(NO_LOGIN.getCode(), NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        // 登录验证成功，放行
        // 希望在 controller 中直接获取用户的信息，怎么获取
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果不删除 ThreadLocal 中用完的信息，会有内存泄露的风险
        UserThreadLocal.remove();
    }
}
